package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.ParameterMapping;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.util.List;

/**
 * @ClassName BaseStatementHandler
 * @Description TODO
 * @Auth ying.xiao
 * @Date 2021/1/29
 * @Version 1.0.0
 */
public abstract class BaseStatementHandler implements StatementHandler{

    protected Configuration configuration;
    protected MappedStatement mappedStatement;
    protected Object[] params;

    public BaseStatementHandler(Configuration configuration, MappedStatement mappedStatement, Object[] params){
        this.configuration = configuration;
        this.mappedStatement = mappedStatement;
        this.params = params;
    }

    @Override
    public void prepareParams(PreparedStatement preparedStatement, BoundSql boundSql) throws Exception {
        // 4. 设置参数
        //获取到了参数的全路径
        String parameterType = mappedStatement.getParamterType();
        Class<?> parameterizeClass = getClassType(parameterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            if(parameterizeClass.getPackage().getName().equals("java.lang")){
                preparedStatement.setObject(i+1,params[i]);
                continue;
            }
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            //反射
            Field declaredField = parameterizeClass.getDeclaredField(content);
            //暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);

            preparedStatement.setObject(i+1,o);

        }
    }
    protected Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if(paramterType!=null){
            Class<?> aClass = Class.forName(paramterType);
            return aClass;
        }
        return null;

    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        Class<?> aClass = Class.forName("java.lang.String");
        System.out.println(aClass.getTypeName());
        System.out.println(aClass.getName());
        System.out.println(aClass.getPackage().getName().equals("java.lang"));
        Field declaredField = aClass.getDeclaredField("value");
        //暴力访问
        declaredField.setAccessible(true);
        Object o = declaredField.get("xyy");
        String str = (String) o;
        System.out.println(o);
        System.out.println(str);
    }
}
